package com.kevis.zhunblog.admin.controller.modules.sys;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.kevis.webCommon.constant.UrlConstant;
import com.kevis.webCommon.vo.easyui.TreeVo;
import com.kevis.zhunblog.admin.controller.base.BaseController;
import com.kevis.zhunblog.core.entities.BaseClassEntity;
import com.kevis.zhunblog.core.entities.ClassArticleEntity;
import com.kevis.zhunblog.core.entities.PowerMenuEntity;
import com.kevis.zhunblog.service.ClassArticleService;
import com.kevis.zhunblog.service.PowerMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 项目入口
 */
@Controller
public class SysEntranceController extends BaseController {
//    @Autowired
//    private HttpServletRequest request;

    @Autowired
    private HttpSession session;

    @Autowired
    private ClassArticleService classArticleService;

    @Autowired
    private PowerMenuService powerMenuService;

    /**
     * 获取登录视图
     *
     * @param request
     * @return
     */
    @GetMapping(value = UrlConstant.ADMIN_LOGIN_URL)
    public String login(HttpServletRequest request) {
        return "login";
    }

    /**
     * 当初为了测试 .failureForwardUrl("/hhm/login")//要跳转到post的方法才生效
     *  现在改成异步登录了，所以这个方法也就先注释了
     * @param request
     * @return

    //@PostMapping(value = UrlConstant.ADMIN_LOGIN_URL)
    public String postLogin(HttpServletRequest request){
    return "login";
    }
     */


    /**
     * 获取主体框架,登录进入后的页面
     *
     * @return
     */
    @GetMapping({"/index"})
    public String adminIndex() {
        return "index";
    }

    /**
     * 进入后主页(内容页)
     *
     * @return
     */
    @ResponseBody
    @GetMapping({"/console"})
    public ModelAndView console() {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("console/console");
        return mv;
    }

    /**
     * Describe:无权限页面
     * Return:返回403页面
     */
    @GetMapping("error/403")
    public ModelAndView noPermission() {
        return jumpPage("error/403");
    }

    /**
     * Describe:找不带页面
     * Return:返回404页面
     */
//    @GetMapping("error/404")
//    public ModelAndView notFound() {
//        return jumpPage("error/404");
//    }

    /**
     * Describe:异常处理页
     * Return:返回500界面
     */
    @GetMapping("error/500")
    public ModelAndView onException() {
        return jumpPage("error/500");
    }

//    @PostMapping("logout")
//    public String logout(){
//        return "login";
//    }

    @RequestMapping("/{tableName}/GetTreeCombo")
    @ResponseBody
    public List GetTreeCombo(@PathVariable("tableName") String tableName
                             //, @RequestParam(defaultValue = "0", required = false) Integer parentId
            , @RequestParam(defaultValue = "0", required = false, name = "id") Integer id
            , @RequestParam(defaultValue = "false", required = false) Boolean isRoot
            , @RequestParam(defaultValue = "false", required = false) Boolean isThis
            , @RequestParam(defaultValue = "false", required = false) Boolean isAllStatus
            , @RequestParam(required = false) String Default
    ) {
        List<TreeVo> result = new ArrayList<TreeVo>();
        List<TreeVo> list = GetTreeAjax(tableName, id, isRoot, isThis, isAllStatus, Default);
        if (id > 0) {
            result = list;
        } else {
            result.add(0, new TreeVo(0, " 一级分类或顶级分类 ", list.size(), "1", "icon-tree", list));
        }
        return result;
    }

    //@Cached(area = "kevis",name="dfdfdf", expire = 3600)
    @RequestMapping("/{tableName}/GetTreeAjax")
    @ResponseBody
    public List<TreeVo> GetTreeAjax(@PathVariable("tableName") String tableName
                                    //, @RequestParam(defaultValue = "0", required = false) Integer parentId
            , @RequestParam(defaultValue = "0", required = false, name = "id") Integer id
            , @RequestParam(defaultValue = "false", required = false) Boolean isRoot
            , @RequestParam(defaultValue = "false", required = false) Boolean isThis
            , @RequestParam(defaultValue = "false", required = false) Boolean isAllStatus
            , @RequestParam(required = false) String Default
    ) {
        class InnerClass<T extends BaseClassEntity> {
            <E extends BaseClassEntity> List<TreeVo> toTree(List<E> list) {
                if (list != null && list.size() > 0) {
                    return list.stream().map(t -> {
                        TreeVo treeVo = new TreeVo();
                        treeVo.setId(t.getId());
                        treeVo.setText(t.getTitle());
                        //treeVo.setChildren(t.getChildren());
                        treeVo.setChildren(toTree(t.getChildren()));//如果前端想每次点一下再来取,这个就要注释
                        treeVo.setCount(t.getChildcount());
                        treeVo.setState(t.getState());
                        return treeVo;
                    }).collect(Collectors.toList());
                }
                return null;
            }
        }

        boolean _IsThis = id > 0 ? false : isThis; //ajax异步获取树 不读取本身
        List<TreeVo> result = new ArrayList<TreeVo>();
        List<TreeVo> list = new ArrayList<TreeVo>();
        switch (tableName.toLowerCase()) {
            case "article":
//                System.out.println(classArticleService.cache1());
//                System.out.println(classArticleService.cache2());
//
//
//                System.out.println(classArticleService.cache1());
//                System.out.println(classArticleService.cache2());
//
//                List<ClassArticleEntity> hjk = classArticleService.hjk();
//                String fgh = classArticleService.fgh();
                //新闻 栏目(分类)
                List<ClassArticleEntity> list1 = classArticleService.GetListTreeByParentId(id > 0 ? id : 0, _IsThis, isAllStatus);
                //LambdaQueryWrapper<ClassArticleEntity> wrapper = new LambdaQueryWrapper<>();
                //wrapper.eq(ClassArticleEntity::getParentId,parentId);
                //List<ClassArticleEntity> list1 = classArticleService.selectByParentId((ClassArticleEntity)->wrapper,parentId,isAllStatus);
                //List<ClassArticleEntity> list1 = classArticleService.selectByParentId(parentId,isAllStatus);
                list = new InnerClass<ClassArticleEntity>().toTree(list1);
                break;
            default:
                break;
        }
        //是否显示 根路径
        if (isRoot && id == 0) {
            if (id > 0) {
                //如果不是取跟节点的话就不要组装 [一级分类或顶级分类] 节点了
                return list;
            } else {
                TreeVo tv = new TreeVo();
                tv.setId(0);
                tv.setText(!StringUtils.hasLength(Default) ? (" 一级分类或顶级分类 ") : Default);
                tv.setIconCls("icon-tree");
                tv.setChildren(list);
                //tv.setCount(list.size());
                result.add(tv);
            }
            return result;
        } else {
            return list;
        }
    }

    @GetMapping(value = {"/zhun/post.do"})
    public String Get(@RequestParam(value = "actionguid") String ActionGUID, HttpServletRequest request) {
        return Post(ActionGUID, request);
    }

    @PutMapping(value = {"/zhun/post.do"})
    public String put(@RequestParam(value = "actionguid") String ActionGUID, HttpServletRequest request) {
        return Post(ActionGUID, request);
    }

    @DeleteMapping(value = {"/zhun/post.do"})
    public String delete(@RequestParam(value = "actionguid") String ActionGUID, HttpServletRequest request) {
        return Post(ActionGUID, request);
    }

    /**
     * 统一的访问路径
     *
     * @param ActionGUID RequestParam区分大小写
     * @param request
     * @return
     */
    @PostMapping(value = {"/zhun/post.do"})
    public String Post(@RequestParam(value = "actionguid") String ActionGUID, HttpServletRequest request) {
        System.out.println(ActionGUID);
        String requestURI = request.getRequestURI();
        LambdaQueryWrapper<PowerMenuEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PowerMenuEntity::getGuid, ActionGUID);
        PowerMenuEntity action = powerMenuService.getOne(wrapper);
        if (action == null) {
            throw new RuntimeException("菜单不存在,请联系管理员");
        }
        request.setAttribute("ActionGUID", ActionGUID);
        //request.setAttribute("expectedRole","53");
        //跳转，地址栏的地址会变
        //return "redirect:"+action.getF_LinkUrl();
        //转发，地址栏的地址不会变
        //return "forward:" + (request.getContextPath() + "/" + action.getUrl() + "?" + request.getQueryString());
        //return "forward:" + (action.getUrl() + "?" + request.getQueryString());
        if (action.getIsJumpExternalUrl()) {
            return "redirect:" + action.getUrl();
        } else {
            String restfulUrl = "";
            String queryString = request.getQueryString();
            String queryStringHandle = "";

            if(StringUtils.hasLength(queryString)) {
                int beginIndexOf = queryString.indexOf("**");
                int lastIndexOf = queryString.lastIndexOf("**");
                if (beginIndexOf >= 0 && lastIndexOf > beginIndexOf) {
                    restfulUrl = queryString.substring(beginIndexOf + 2, lastIndexOf);
                    queryStringHandle = queryString.substring(0, beginIndexOf) + queryString.substring(lastIndexOf + 2);
                    //直接赋值的话,不会生效,需要重新定义一个变量接收
                    //queryString = queryString.substring(0, beginIndexOf) + queryString.substring(lastIndexOf + 2);
                }
            }
            String url = (action.getUrl() + restfulUrl + "?" + queryStringHandle);
            url = url.replaceAll("//", "/");
            return "forward:" + url;
        }
    }
}
